/**  
 * All rights Reserved, Designed By Android_Robot   
 * @Title:  ZoneTuiJianFragment.java   
 * @Package com.jiyi.activity.zone   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: HYM     
 * @date:   2017-6-6 上午10:47:48   
 * @version V1.0     
 */
package com.jiyi.activity.zone;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.hyphenate.easeui.EaseConstant;
import com.jiyi.adapter.CommonAdapter;
import com.jiyi.adapter.ViewHolder;
import com.jiyi.bean.zone.HuoDongDetailJson;
import com.jiyi.bean.zone.QunZuDetailJson;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.bean.zone.ZoneQunZuBean;
import com.jiyi.bean.zone.ZoneTuiJianJson;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.ClouldChatType;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.HuoDongStatuEvent;
import com.jiyi.inteface.HuoDongPopInterface;
import com.jiyi.inteface.QunZuPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.HuoDongPopView;
import com.jiyi.view.QunZuPopView;
import com.swift.bean.BannerBean;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.maintenance.utils.ZoneHuoDongUtil;
import com.swift.utils.DateUtils;
import com.swift.utils.GlideUtil;
import com.jiyi.widget.SlideShowView;
import com.swift.widget.TranslucentImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ZoneTuiJianFragment extends Fragment implements
		HuoDongPopInterface, QunZuPopInterface {

	@BindView(R.id.zone_tuijian_lunbo)
	SlideShowView lunbo;
	@BindView(R.id.gvQunZuTuiJian)
	GridView gvQunZuTuiJian;
	// @Bind(R.id.lvHuoDong)
	// ListView lvHuoDong;
	@BindView(R.id.llHuoDong)
	LinearLayout llHuoDong;
	@BindView(R.id.ivAllHuoDong)
	ImageView ivAllHuoDong;
	@BindView(R.id.ivAllQunZu)
	ImageView ivAllQunZu;

	HuoDongPopView mHuoDongPopView;
	QunZuPopView mQunZuPopView;

	List<ZoneQunZuBean> mQunZuList = new ArrayList<ZoneQunZuBean>();
	List<ZoneHuoDongBean> mHuoDongList = new ArrayList<ZoneHuoDongBean>();
	private CommonAdapter mAdapter, mHuoDongAdapter;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_zone_tuijian, null,
				false);
		ButterKnife.bind(this, view);
		init();
		return view;
	}
	
	@Override
	public void onStart() {
		super.onStart();
		EventBus.getDefault().register(this);
	}
	
	@Subscribe
	public void onRefreshHuoDong(HuoDongStatuEvent huoDongStatuEvent)
	{
		int statu = huoDongStatuEvent.statu;
		String huoDongId = huoDongStatuEvent.huoDongId;
		for (int i = 0; i < mHuoDongList.size(); i++) {
			if (mHuoDongList.get(i).getId().equals(huoDongId)) {
				mHuoDongList.get(i).setFlag(statu);
				setHuoDongData();
				break;
			}
		}
	}
	
	@Override
	public void onStop() {
		EventBus.getDefault().unregister(this);
		super.onStop();
	}

	private void init() {
		getTuiJianData();
		// setHuoDongData();
		mHuoDongPopView = new HuoDongPopView(this.getContext(), this);
		mQunZuPopView = new QunZuPopView(this.getContext(), this);
	}

	/**
	 * @author: HYM
	 * @Title: getTuiJianData
	 * @Description: TODO(获取推荐数据) void
	 * @date: 2017-7-13
	 */
	private void getTuiJianData() {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

		VolleyRequest.StringRequestPost(getContext(), WebApi.ZONE_TUIJIAN, "",
				params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							if (getActivity() == null || getActivity().isFinishing()) {
								return;
							}
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								ZoneTuiJianJson temp = new Gson().fromJson(
										result, ZoneTuiJianJson.class);
								if (temp != null && temp.getData() != null) {
									// 获取到轮播的图片
									List<BannerBean> banner = temp.getData()
											.getBannerList();
									setLunBo(banner);
									// 设置群组数据
									List<ZoneQunZuBean> qunzu = temp.getData()
											.getGroupList();
									mQunZuList.clear();
									mQunZuList.addAll(qunzu);
									setQunZuAdapter();
									// 设置活动数据
									List<ZoneHuoDongBean> huodong = temp.getData().getActList();
									mHuoDongList.clear();
									mHuoDongList.addAll(huodong);
									setHuoDongData();
								}
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	/**
	 * @author: HYM
	 * @Title: setHuoDongData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-6
	 */
	private void setHuoDongData() {
		llHuoDong.removeAllViews();
		for (int i = 0; i < mHuoDongList.size(); i++) {
			final ZoneHuoDongBean obj = mHuoDongList.get(i);
			View view = LayoutInflater.from(getContext()).inflate(
					R.layout.item_zone_huodong, null, false);
			TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
			tvTitle.setText(obj.getTheme());
			TranslucentImageView ivLogo = (TranslucentImageView) view
					.findViewById(R.id.ivHuoDongLogo);
			ivLogo.setTextString(obj.getAttendPer() + "人参与");
			GlideUtil.load(getContext(), obj.getCover(), ivLogo);
			TextView tvAddress = (TextView) view.findViewById(R.id.tvAddress);
			tvAddress.setText(obj.getAddress());
			TextView tvStartDate = (TextView) view.findViewById(R.id.tvStartDate);
			tvStartDate.setText(DateUtils.fmtDateToStr(obj.getStart_time(), DateUtils.YMD_FORMAT));
			TextView tvEndDate = (TextView) view.findViewById(R.id.tvEndDate);
			tvEndDate.setText(DateUtils.fmtDateToStr(obj.getEnd_time(), DateUtils.YMD_FORMAT));
			TextView tvJoin = (TextView) view.findViewById(R.id.tvJoin);
			//1.等待报名,2.用户可参与，3.等待开始，4.进行中，5.活动结束，6.活动取消
			int status = obj.getFlag();
			ZoneHuoDongUtil.setStatus(tvJoin, status);
			
			tvJoin.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					//加载活动的数据
					getHuoDongDetail(obj.getId());
				}
			});
			
			
			llHuoDong.addView(view);
			View spi = new View(getContext());
			spi.setBackgroundColor(getResources().getColor(R.color.spi_grey));
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
					10);
			spi.setLayoutParams(params);
			llHuoDong.addView(spi);
		}

	}

	/**
	 * @author: HYM
	 * @Title: setAdapter
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-6
	 */
	private void setQunZuAdapter() {
		mAdapter = new CommonAdapter<ZoneQunZuBean>(getContext(), mQunZuList,
				R.layout.item_zone_tuijian_qunzu) {

			@Override
			public void convert(ViewHolder holder, ZoneQunZuBean t) {
				holder.setImage(R.id.civQunZuLogo, t.getGroup_head());
				holder.setText(R.id.tvQunZuName, t.getName());
			}
		};
		int size = mQunZuList.size();
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		float density = dm.density;
		int allWidth = (int) (84 * size * density);
		int itemWidth = (int) (80 * density);
		LayoutParams params = new LayoutParams(
				allWidth, LayoutParams.MATCH_PARENT);
		gvQunZuTuiJian.setLayoutParams(params);
		gvQunZuTuiJian.setColumnWidth(itemWidth);
		gvQunZuTuiJian.setHorizontalSpacing(4);
		gvQunZuTuiJian.setStretchMode(GridView.NO_STRETCH);
		gvQunZuTuiJian.setNumColumns(size);
		gvQunZuTuiJian.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();

		gvQunZuTuiJian.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ZoneQunZuBean zoneQunZuBean = (ZoneQunZuBean) parent
						.getAdapter().getItem(position);
				if (zoneQunZuBean.getIs_in_group()) {
					Intent intent2 = new Intent(getContext(),
							EasemobChatActivity.class);
					intent2.putExtra(ClouldChatType.INTENT_USER_PIC,
							zoneQunZuBean.getGroup_head());
					intent2.putExtra("id", zoneQunZuBean.getId());
					intent2.putExtra("name", zoneQunZuBean.getName());
					intent2.putExtra("easemobgid",
							zoneQunZuBean.getHx_group_id());
					intent2.putExtra(ClouldChatType.INTENT_Group_Id,
							zoneQunZuBean.getId());
					intent2.putExtra("easeMobChatType",
							EaseConstant.CHATTYPE_GROUP);
					startActivity(intent2);
				} else {
					getQunZuDetail(zoneQunZuBean.getId());
				}
			}
		});
	}

	/**
	 * @author: HYM
	 * @Title: setLunBo
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-6-6
	 */
	private void setLunBo(List<BannerBean> bannerList) {
		lunbo.setBannerList(bannerList);
	}

	/**
	 * <p>
	 * Title: OnSureListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see HuoDongPopInterface#OnSureListener()
	 */
	@Override
	public void OnSureListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnCancleListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see HuoDongPopInterface#OnCancleListener()
	 */
	@Override
	public void OnCancleListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnShowListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see HuoDongPopInterface#OnShowListener()
	 */
	@Override
	public void OnShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnHideListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see HuoDongPopInterface#OnHideListener()
	 */
	@Override
	public void OnHideListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnQZSureListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see QunZuPopInterface#OnQZSureListener()
	 */
	@Override
	public void OnQZSureListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnQZCancleListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see QunZuPopInterface#OnQZCancleListener()
	 */
	@Override
	public void OnQZCancleListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnQZShowListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see QunZuPopInterface#OnQZShowListener()
	 */
	@Override
	public void OnQZShowListener() {
		// TODO Auto-generated method stub

	}

	/**
	 * <p>
	 * Title: OnQZHideListener
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @see QunZuPopInterface#OnQZHideListener()
	 */
	@Override
	public void OnQZHideListener() {
		// TODO Auto-generated method stub

	}

	@OnClick({ R.id.ivAllQunZu, R.id.ivAllHuoDong })
	public void onClick(View veiw) {
		Intent intent = null;
		switch (veiw.getId()) {
		case R.id.ivAllQunZu:
			intent = new Intent(getActivity(), ZoneAllQunZuActivity.class);
			startActivity(intent);
			break;
		case R.id.ivAllHuoDong:
			intent = new Intent(getActivity(), ZoneAllHuoDongActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
	
	/**   
	 * @author: HYM 
	 * @Title: getHuoDongDetail   
	 * @Description: TODO(获取活动详情)   
	 * @param huoDongId void 
	 * @date: 2017-7-17
	 */  
	void getHuoDongDetail(String huoDongId)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", huoDongId);

		VolleyRequest.StringRequestPost(getContext(), WebApi.ZONE_HUODONG_DETAIL, "",
				params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								HuoDongDetailJson temp = new Gson().fromJson(
										result, HuoDongDetailJson.class);
								mHuoDongPopView.showPopWindow(temp.getData());
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}

	/**   
	 * @author: HYM 
	 * @Title: getHuoDongDetail   
	 * @Description: TODO(获取活动详情)   
	 * @date: 2017-7-17
	 */  
	void getQunZuDetail(String qunZuId)
	{
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", qunZuId);

		VolleyRequest.StringRequestPost(getContext(), WebApi.ZONE_QUNZU_DETAIL, "",
				params, new StringInterface(getContext()) {

					@Override
					public void stringSuccess(String result) {
						try {
							JSONObject obj = new JSONObject(result);
							String status = obj.getString("status");
							String info = obj.getString("info");
							if (status.equals("200")) {
								QunZuDetailJson temp = new Gson().fromJson(
										result, QunZuDetailJson.class);
								mQunZuPopView.showPopWindow(temp.getData());
							} else {
								ToastUtil.getInstances().showMsg(info);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						} finally {
						}
					}

					@Override
					public void stringError(VolleyError error) {
						ToastUtil.getInstances().showMsg(R.string.err_http_response);
					}
				});
	}
}
